<template>
  <el-dialog title="临时盘点新增" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
		<el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form class="verify-form" :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-row :gutter="15">
        <el-col :span="8">
          <el-form-item label="盘点仓位" prop="stockId">
            <el-select v-model="dataForm.stockId" placeholder="请选择">
              <el-option v-for="item in stockOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘盈盘亏" prop="brandId">
            <el-select v-model="dataForm.checkType" placeholder="请选择" @change="checkTypeChangeHandle">
              <el-option v-for="item in checkTypeOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点类型">
            <el-select v-model="dataForm.ctgId" placeholder="请选择" :disabled="dataList.length > 0">
              <el-option v-for="item in ctgOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="备注" prop="stockId">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="20">
          <el-form-item label-width="0">
            <el-button type="primary" @click="addGoodsBySingle">单品添加商品</el-button>
            <el-button type="primary" @click="barcodeScan()">条码扫描</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item style="float: right;">
            <el-button type="danger" @click="delTableData">删除</el-button>
          </el-form-item>
        </el-col>

      </el-row>

      <el-table :data="dataList" border v-loading="dataListLoading" show-summary :summary-method="getSummaries" @selection-change="handleSelectionChange">
        <el-table-column key="1" type="selection" width="55"></el-table-column>
        <el-table-column key="2" prop="code" label="商品代码"></el-table-column>
        <el-table-column key="3" prop="barcode" label="商品条码"></el-table-column>
        <el-table-column key="4" prop="name" label="商品名称"></el-table-column>
        <el-table-column key="5" prop="spec" label="型号" width="120"></el-table-column>
        <el-table-column key="6" prop="goodsQuantity" label="库存数量" v-if="dataForm.checkType == 2"></el-table-column>
        <el-table-column key="7" prop="number" label="数量">
          <template slot-scope="scope">
            <el-form-item :prop="'infos.' + scope.$index + '.number'" :rules="dataRule.quantity" label-width="0px">
              <el-input v-model="scope.row.number" :ref="'number'+scope.$index" @input="numberChangeHandle($event,scope.$index)" @keyup.enter.native="enterChange(scope.$index)"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
      </el-table>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch v-model="dataForm.checkStatus" active-text="保存并审核" inactive-value="0" active-value="1" style="margin-left: 15px;"  v-if="userInfo.lessDeptId == 1"></el-switch>
    </span>
    <single-goods v-if="singleGoodsVisible" ref="singleGoodsAdd" @refreshForm="updateFormData"></single-goods>
    <!-- 弹窗，条码扫描  -->
    <barcode-scan v-if="barcodeVisible" ref="barcodeDialog" @refreshData="getBarcodeGoodsData"></barcode-scan>
  </el-dialog>
</template>

<script>
  import { saveNewCheckOrder, saveAndAuditOrder, getStockDataList, getCtgDataList } from "@/api/eims/check";
  import SingleGoods from "@/components/business/CheckStorage";
  // import SingleGoods from "./goods-search-single";
  import { mapGetters } from "vuex"
  import { getStockInfo, getStockList,getStockObj } from "@/api/eims/stock"

  import BarcodeScan from '@/components/business/BarcodeScan'


  export default {
    data() {
      let quantityValid = function(rule,value,callback){
        const reg = /^[1-9]\d*?$/
        if(value === ''){
          callback(new Error('请输入商品数量'))
        }else{
          if(reg.test(value)){
            callback()
          }else{
            callback(new Error('商品数量必须为正整数'))
          }
        };
      }
      return {
        ischeck: false,
        visible: false,
        dataForm: {
          id: 0,
          stockId: "",
          ctgId: "",
          checkType: "",
          memo: "",
          checkStatus: "0",
          infos: []
        },
        stockOptions: [],
        ctgOptions: [],
        checkTypeOptions: [
          { value: 1, name: "盘盈" },
          { value: 2, name: "盘亏" }
        ],
        dataList: [],
        dataListLoading: false,
        dataRule: {
          quantity: [
            {required: true, validator: quantityValid,trigger: 'blur'}
          ]
        },
        singleGoodsVisible: false,
        barcodeVisible: false,
        selectionList: []
      };
    },
    components: {
      SingleGoods,
      BarcodeScan
    },
    computed: {
      ...mapGetters(["permissions", "userInfo"])
    },
    methods: {
      init(id) {
        this.getStockList();
        this.getCtgList();
        this.dataForm.checkStatus = "0";
        for (let key in this.dataForm) {
          if (key == 'infos') {
            this.dataForm[key] = []
          } else {
            this.dataForm[key] = ''
          }
        }
        this.dataList = []
        this.dataForm.id = id || 0;
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          if (this.dataForm.id) {

          }
        });
      },
      // 盘点类型改变
      checkTypeChangeHandle(val){
        this.dataList = []
        this.dataForm.infos = []
      },
      // 打开商品列表弹窗
      addGoodsBySingle() {
        if (!this.dataForm.ctgId) {
          this.$message.warning("请选择盘点类别");
          return
        }
        if (!this.dataForm.stockId) {
          this.$message.warning("请选择盘点仓位");
          return
        }
        let params = {
            stockId: this.dataForm.stockId,
            ctgId: this.dataForm.ctgId,
            checkType: this.dataForm.checkType
          };
        let data = {
          paramsData: params,
          tableData: this.dataList
        };
        this.singleGoodsVisible = true;
        this.$nextTick(() => {
          this.$refs.singleGoodsAdd.init(data);
        });
      },
      handleSelectionChange(val) {
        this.selectionList = val;
      },
      // 删除选中的商品
      delTableData() {
        this.selectionList.forEach((item,index) => {
          for(let i = 0; i < this.dataList.length; i++){
            if(this.dataList[i] == item){
              this.dataList.splice(i,1)
              this.dataForm.infos.splice(i,1)
            }
          }
          this.selectionList = []
        })
      },
      //更新表单数据
      updateFormData(data) {
        this.dataList = data
        let list = []
        data.forEach(item => {
          list.push({
            code: item.code,
            barcode: item.barcode,
            goodsId: item.id,
            goodsName: item.name,
            spec: item.spec,
            stockId: item.stockId,
            number: ''
          });
        })
        this.dataForm.infos = list
      },
      numberChangeHandle(val,index1) {

        if(this.dataForm.checkType == 2){
          if(val > this.dataList[index1].goodsQuantity){
            this.dataList[index1].number = ''
            this.$message.warning('盘亏数量不得大于库存数量')
            return false
          }
        }
        this.dataForm.infos.forEach((item, index) => {
          item.number = this.dataList[index].number;
        });


      },
			// 回车切换
      enterChange(index){
        if(this.$refs['number'+(index*1 + 1)]){
          this.$refs['number'+(index*1 + 1)].focus()
        }else{
          this.$refs['number0'].focus()
        }
      },
			//  条码扫描
			barcodeScan() {
			  if (!this.dataForm.ctgId) {
			    this.$message.warning("请选择盘点类别");
			    return
			  }
			  if (!this.dataForm.stockId) {
			    this.$message.warning("请选择盘点仓位");
			    return
			  }
			  this.barcodeVisible = true
			  this.$nextTick(() => {
			    this.$refs.barcodeDialog.init(this.dataForm.outStockId)
			  })
			},
      //  条码扫描获取的数据
      getBarcodeGoodsData(data) {
        let obj = {...data}
        obj.goodsId = obj.id
        obj.name = obj.viewGoodsName
        let result = this.dataList.some(item => {
          return item.goodsBarcode == obj.goodsBarcode
        })

        if(result){
          this.dataList.forEach(item => {
            if(item.goodsBarcode == obj.goodsBarcode){
              item.allocationQuantity += 1
            }
          })
        }else{
          this.dataList.push(obj)
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            if (this.dataForm.stockId == "") {
              this.$message.warning("请选择盘点仓位");
              return;
            }
            if (this.dataForm.checkType == "") {
              this.$message.warning("请选择盘点类型");
              return;
            }
            saveNewCheckOrder(this.dataForm).then(result => {
              if(result.data.code == '0'){
                this.$message.success("新增成功");
                this.visible = false;
                this.$emit("refreshDataList");
              }else{
                this.$message.error(result.data.msg)
              }
              this.ischeck = false
            }).catch(() => {
              this.ischeck = false
            })
          }else{
            this.ischeck = false
          }
        });
      },

      /*
       * *  获取所需数据字典
       * *     getStockList  ------- 获取仓位列表数据字典
       * *     getCtgList    ------- 获取商品类别列表数据字典
       */
      getStockList() {
        let deptId = this.userInfo.lessDeptId;
        let options = [];
        if (deptId == 1) {
          getStockList().then(result => {
            if(result.data.code == '0'){
              let dataList = result.data.data;
              dataList.forEach(item => {
                options.push({
                  value: item.id,
                  name: item.name
                });
              });
            }else{
              this.$message.error(result.data.msg)
            }
          });
        } else {
          getStockInfo(deptId).then(result => {
            if(result.data.code == '0'){
              let info = result.data.data
              info.forEach(item => {
                options.push({
                  value: item.id,
                  name: item.name
                });
              })
            }else{
              this.$message.error(result.data.msg)
            }
          });
        }
        this.stockOptions = options;
      },
      getCtgList() {
        getCtgDataList().then(result => {
          if(result.data.code == '0'){
            let dataList = result.data.data.records;
            let options = [];
            dataList.forEach(item => {
              options.push({
                value: item.id,
                name: item.name
              });
            });
            this.ctgOptions = options;
          }else{
            this.$message.error(result.data,msg)
          }
        });
      },
      //  合计
      getSummaries(param) {
        const { columns, data } = param;
        let sums = [];
        let zIndex = ''
        if(this.dataForm.checkType == 1){
          zIndex = 5
          sums = ['','','','','','0']
        }else {
          zIndex = 6
          sums = ['','','','','','','0']
        }
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (!values.every(value => isNaN(value))) {

            if(index == zIndex){
              sums[index] = '合计： ' + values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0)
            }
          }
        });
        return sums;
      },
    }
  };
</script>
<style lang="scss" scoped>
  /deep/ .el-table {
    display: flex;
    flex-direction: column;
  }
  /deep/ .el-table__body-wrapper {
    order: 1;
  }
</style>
